import Vue from 'vue'
import Vuex from 'vuex'
import VueCookies from 'vue-cookies'

Vue.use(Vuex)
Vue.use(VueCookies);

function saveToSessionStorage(key, data) {
  saveToStorage("sessionStorage", key, data)
}

function saveToLocalStorage(key, data) {
  saveToStorage("localStorage", key, data)
}

function saveToStorage(place, key, data) {
  let storage = "";
  if (place === 'localStorage') {
    storage = window.localStorage;
  } else if (place === 'sessionStorage') {
    storage = window.sessionStorage;
  }

  if (storage === "") return;

  /* 浏览器关闭之后就会清除 */
  try {
    storage.setItem(key, data);
  } catch (e) {
    if (e.code === QUOTA_EXCEEDED_ERR_CODE) {
      Vue.prototype.$vue.$Message.error("浏览器本地存储空间已满，空间重置");
      /*超出大小限制之后，清空、强制写入*/
      storage.clear();
      storage.setItem(key, data);
    }
  }
}

function getFromLocalStorage(state, key) {
  if (!state[key]) {
    let storageValue = window.localStorage.getItem(key);
    if (!!storageValue) {
      state[key] = storageValue;
    } else {
      state[key] = "";
    }
  }
  //console.log(key + " => " + state[key]);
  return state[key];
}

function getFromSessionStorage(state, key) {
  if (!state[key]) {
    let storageValue = window.sessionStorage.getItem(key);
    if (!!storageValue) {
      state[key] = storageValue;
    } else {
      state[key] = "";
    }
  }
  console.log(key + " => " + state[key]);
  return state[key];
}

const moduleCivilAction = {
  state: {
    docSelected: ""
  },
  mutations: {
    saveDocSelected: (state, info) => {
      state.docSelected = info;
      const jsonStr = JSON.stringify(info);
      saveToSessionStorage('moduleCivilAction.docSelected', jsonStr);
    },
    saveDocSelectedForOrder: (state, info) => {
      state.docSelectedForOrder = info;
      const jsonStr = JSON.stringify(info);
      saveToSessionStorage('moduleCivilAction.docSelectedForOrder', jsonStr);
    },
    saveOrder: (state, info) => {
      const key = 'moduleCivilAction.order';
      state[key] = info;
      const jsonStr = JSON.stringify(info);
      saveToSessionStorage(key, jsonStr);
    },
    saveCustormerDiscount: (state, info) => {
      const key = 'moduleCivilAction.custormerDiscount';
      state[key] = info;
      const jsonStr = JSON.stringify(info);
      saveToSessionStorage(key, jsonStr);
    }
  },
  getters: {
    docSelected: function(state) {
      const key = 'moduleCivilAction.docSelected';
      if (!state.docSelected) {
        const jsonStr = window.sessionStorage.getItem(key);
        if (!jsonStr) {
          state.docSelected = [];
          saveToSessionStorage(key, []);
        } else {
          try {
            state.docSelected = JSON.parse(jsonStr);
          } catch (e) {
            /*如果出现异常了，则需要清除sessionStorage*/
            state.docSelected = "";
            saveToSessionStorage(key, "");
          }
        }
      }
      return state.docSelected;
    },
    docSelectedForOrder: function(state) {
      const key = 'moduleCivilAction.docSelectedForOrder';
      if (!state.docSelectedForOrder) {
        const jsonStr = window.sessionStorage.getItem(key);
        if (!jsonStr) {
          state.docSelectedForOrder = [];
          saveToSessionStorage(key, []);
        } else {
          try {
            state.docSelectedForOrder = JSON.parse(jsonStr);
          } catch (e) {
            /*如果出现异常了，则需要清除sessionStorage*/
            state.docSelectedForOrder = "";
            saveToSessionStorage(key, "");
          }
        }
      }
      return state.docSelectedForOrder;
    },
    order: function(state) {
      const key = 'moduleCivilAction.order';
      if (!state[key]) {
        const jsonStr = window.sessionStorage.getItem(key);
        if (!jsonStr) {
          state[key] = [];
          saveToSessionStorage(key, []);
        } else {
          try {
            state[key] = JSON.parse(jsonStr);
          } catch (e) {
            /*如果出现异常了，则需要清除sessionStorage*/
            state[key] = "";
            saveToSessionStorage(key, "");
          }
        }
      }
      return state[key];
    },
    custormerDiscount: function(state) {
      const key = 'moduleCivilAction.custormerDiscount';
      if (!state[key]) {
        const jsonStr = window.sessionStorage.getItem(key);
        if (!jsonStr) {
          state[key] = [];
          saveToSessionStorage(key, []);
        } else {
          try {
            state[key] = JSON.parse(jsonStr);
          } catch (e) {
            /*如果出现异常了，则需要清除sessionStorage*/
            state[key] = "";
            saveToSessionStorage(key, "");
          }
        }
      }
      return state[key];
    }
  },
  actions: {
    saveDocSelected: (context, info) => {
      context.commit("saveDocSelected", info);
    },
    saveDocSelectedForOrder: (context, info) => {
      context.commit("saveDocSelectedForOrder", info);
    },
    saveOrder: (context, info) => {
      context.commit("saveOrder", info);
    },
    saveCustormerDiscount: (context, info) => {
      context.commit("saveCustormerDiscount", info);
    }
  }
}

export default new Vuex.Store({
  modules: {
    civilAction: moduleCivilAction
  },
  state: {
    accessToken: "",
    refreshToken: "",
    loginRedirectUrl: "",
    /*保存帐户信息*/
    account: "",
    /*保存填写的表单*/
    docForm: ""
  },
  /* Getter相当于vue中的computed计算属性，getter 的返回值会根据它的依赖被缓存起来，
  且只有当它的依赖值发生了改变才会被重新计算，这里我们可以通过定义vuex的Getter来获取，
  Getters 可以用于监听、state中的值的变化，返回计算后的结果 */
  getters: {
    accessToken: function(state) {
      const key = 'accessToken';
      return getFromLocalStorage(state, key);
    },
    refreshToken: function(state) {
      const key = 'refreshToken';
      return getFromLocalStorage(state, key);
    },
    loginRedirectUrl: function(state) {
      const key = 'loginRedirectUrl';
      return getFromSessionStorage(state, key);
    },
    account: function(state) {
      const key = 'account';
      if (!state[key]) {
        const accountJsonStr = window.localStorage.getItem(key);
        try {
          state[key] = JSON.parse(accountJsonStr);
        } catch (e) {
          /*如果出现异常了，则需要清除sessionStorage*/
          state[key] = "";
          saveToLocalStorage(key, "");
        }
      }
      return state[key];
    },
    docForm: function(state) {
      const key = 'docForm';
      if (!state.docForm) {
        const jsonStr = window.localStorage.getItem(key);
        try {
          state.docForm = JSON.parse(jsonStr);
        } catch (e) {
          /*如果出现异常了，则需要清除sessionStorage*/
          state.docForm = "";
          saveToLocalStorage(key, "");
        }
      }
      console.log("restore from localStorage => " + JSON.stringify(state.docForm));
      return state.docForm;
    }
  },
  /* 需要修改targetClassroom值怎么办？如果需要修改store中的值唯一的方法就是提交mutation来修改 */
  mutations: {
    saveAccessToken: (state, data) => {
      const key = 'accessToken';
      state[key] = data;
      saveToLocalStorage(key, data);
    },
    saveRefreshToken: (state, data) => {
      const key = 'refreshToken';
      state[key] = data;
      saveToLocalStorage(key, data);
    },
    saveLoginRedirectUrl: (state, data) => {
      const key = 'loginRedirectUrl';
      state[key] = data;
      saveToSessionStorage(key, data);
    },
    saveAccount: (state, account) => {
      state.account = account;

      const accountJsonStr = JSON.stringify(account);
      /* Vuex保存的变量在浏览器刷新后就会清空，所以需要一直使用的数据应该使用window.localStorage 进行存储*/
      saveToLocalStorage('account', accountJsonStr); //sessionStorage不能保存json对象
    },
    saveDocForm: (state, formData) => {
      state.docForm = formData;
      const jsonStr = JSON.stringify(formData);
      saveToLocalStorage('docForm', jsonStr);
    },
    cleanLoginState:  (state, data) => {
      const keys = ['accessToken', 'refreshToken', 'account'];
      keys.map(item => {
        state[item] = "";
        saveToLocalStorage(item, "");
      })
    }
  },
  /* 官方并不介意我们这样直接去修改store里面的值，而是让我们去提交一个actions，在actions中提交mutation再去修改状态值 */
  actions: {
    saveAccessToken: (context, data) => {
      context.commit("saveAccessToken", data);
    },
    saveRefreshToken: (context, data) => {
      context.commit("saveRefreshToken", data);
    },
    saveLoginRedirectUrl: (context, data) => {
      context.commit("saveLoginRedirectUrl", data);
    },
    saveAccount: (context, account) => {
      context.commit("saveAccount", account);
    },
    saveDocForm: (context, formData) => {
      context.commit("saveDocForm", formData);
    },
    cleanLoginState: (context, data) => {
      context.commit("cleanLoginState", data);
    }
  }
})

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})
